package com.wlyuan.open.aspect;

import com.wlyuan.open.OpenBaseSyncDTO;
import com.wlyuan.open.api.IOpenSyncService;
import lombok.RequiredArgsConstructor;
import lombok.var;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @author lijing
 * @description 源数完成切面
 */
@RequiredArgsConstructor
@Component
@Aspect
public class SourceDataEndAspect {
    private final IOpenSyncService openSyncService;

    @Pointcut("@annotation(com.wlyuan.open.aspect.SourceDataEnd)")
    public void end() {

    }

    @Around("end()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        var parameters = Optional.ofNullable(pjp.getArgs()).orElse(new Object[]{});

        var list = Arrays.asList(parameters);
        var dto = (List<OpenBaseSyncDTO>) (List) list;
        //sourceKey
        var sourceKey = dto.stream().findFirst().get().getSourceKey();
        Object result = null;
        try {
            result = pjp.proceed();
            openSyncService.sourceDataSuccess(sourceKey);
        } catch (Exception e) {
            //失败,异常信息,可用于记录失败原因
            openSyncService.sourceDataFail(sourceKey, getStackMsg(e));
        }
        return result;
    }

    /**
     * 获取格式化堆栈异常信息
     *
     * @param e
     * @return
     */
    private String getStackMsg(Exception e) {
        return ExceptionUtils.getStackTrace(e);
    }

}
